package com.jml.hystrix;

import com.alibaba.fastjson.JSONObject;
import com.jml.hystrix.service.MemberService;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixThreadPoolKey;
import com.netflix.hystrix.HystrixThreadPoolProperties;


public class MemberHystrixCommand extends HystrixCommand<JSONObject> {

	private MemberService memberService;

	public MemberHystrixCommand(MemberService memberService) {
		super(setter());
		this.memberService = memberService;
	}

	//配置服务的隔离机制
	private static Setter setter() {
		// 服务分组
		HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("members");
		// 服务标识
		HystrixCommandKey commandKey = HystrixCommandKey.Factory.asKey("member");
		// 线程池名称
		HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("member-pool");
		// #####################################################
		// 线程池配置 线程池大小为10,线程存活时间15秒 队列等待的阈值为100,超过100执行拒绝策略
		HystrixThreadPoolProperties.Setter threadPoolProperties = HystrixThreadPoolProperties.Setter().withCoreSize(7)
				.withKeepAliveTimeMinutes(15).withQueueSizeRejectionThreshold(2);
		// ########################################################
		// 命令属性配置Hystrix 开启超时
		HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.Setter()
				// 采用线程池方式实现服务隔离
				.withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD)
				// 禁止超时机制
				.withExecutionTimeoutEnabled(false);
		return Setter.withGroupKey(groupKey).andCommandKey(commandKey).andThreadPoolKey(threadPoolKey)
				.andThreadPoolPropertiesDefaults(threadPoolProperties).andCommandPropertiesDefaults(commandProperties);
	}

	//配置服务的降级
	@Override
	protected JSONObject getFallback() {
		JSONObject result = new JSONObject();
		result.put("code","500");
		result.put("msg","服务降级-服务器忙！！");
		return result;
	}

	//表示服务执行的
	@Override
	protected JSONObject run() throws Exception {
		System.out.println("当前memberhystrix线程名称:"+ Thread.currentThread().getName());
		JSONObject getdata = memberService.getdata();
		return getdata;
	}
}
